package com.hj.javaweb.util;

import java.sql.*;

public class JdbcUtil {

    public static final String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC";
    public static final String username = "root";
    public static final String password = "123456";

    public static void main(String[] args) throws SQLException {
//        query();
//        insert();
//        update();
        delete();
    }

    public static void insert() throws SQLException {
        try (Connection connection = DriverManager.getConnection(url, username, password)) {
            try (PreparedStatement ps = connection.prepareStatement("insert into student(name,age,address) values (?,?,?)")) {
                ps.setString(1, "allen");
                ps.setInt(2, 37);
                ps.setString(3, "武汉市武汉经济开发区");
                int i = ps.executeUpdate();
                System.out.println("insert:" + i);
            }
        }
    }

    public static void update() throws SQLException {
        try(Connection connection = DriverManager.getConnection(url,username,password)){
            try(PreparedStatement ps = connection.prepareStatement("update student set name = ? where id = ?")){
                ps.setString(1,"allen1");
                ps.setInt(2,2126053561);
                int i = ps.executeUpdate();
                System.out.println("update:" + i);
            }
        }
    }

    public static void delete() throws SQLException {
        try (Connection connection = DriverManager.getConnection(url,username,password)){
            try(PreparedStatement ps = connection.prepareStatement("delete from student where id = ?")){
                ps.setInt(1,2126053561);
                int i = ps.executeUpdate();
                System.out.println("delete:" + i);
            }
        }
    }

    public static void query() throws SQLException {
        // 获取数据库连接
        try (Connection connection = DriverManager.getConnection(url, username, password)) {
            try (PreparedStatement ps = connection.prepareStatement("select * from student where id = ?")) {
                ps.setObject(1, 1);
                try (ResultSet rs = ps.executeQuery();) {
                    while (rs.next()) {
                        int id = rs.getInt("id");
                        String name = rs.getString("name");
                        int age = rs.getInt("age");
                        String address = rs.getString("address");
                        System.out.println("id: " + id + ", name: " + name + ", age: " + age + ", address: " + address);
                    }
                }
            }
        }
    }
}
